<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>数据Excel导入系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
        }

        .header {
            text-align: center;
            color: white;
            margin-bottom: 30px;
        }

        .header h1 {
            font-size: 36px;
            margin-bottom: 10px;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.2);
        }

        .header p {
            font-size: 16px;
            opacity: 0.9;
        }

        .user-info {
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: rgba(255, 255, 255, 0.2);
            padding: 15px 20px;
            border-radius: 10px;
            margin-bottom: 20px;
            color: white;
        }

        .user-info .username {
            font-size: 16px;
            font-weight: bold;
        }

        .user-info .logout-btn {
            padding: 8px 20px;
            background: rgba(255, 255, 255, 0.3);
            border: 1px solid white;
            border-radius: 6px;
            color: white;
            cursor: pointer;
            transition: all 0.3s;
            font-size: 14px;
        }

        .user-info .logout-btn:hover {
            background: white;
            color: #667eea;
        }

        .tabs {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }

        .tab {
            flex: 1;
            min-width: 200px;
            padding: 15px 20px;
            background: rgba(255, 255, 255, 0.2);
            color: white;
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-radius: 12px;
            cursor: pointer;
            transition: all 0.3s;
            text-align: center;
            font-size: 16px;
            font-weight: bold;
        }

        .tab:hover {
            background: rgba(255, 255, 255, 0.3);
            transform: translateY(-2px);
        }

        .tab.active {
            background: white;
            color: #667eea;
            border-color: white;
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }

        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
        }

        .card {
            background: white;
            border-radius: 12px;
            padding: 30px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            margin-bottom: 20px;
        }

        .card-title {
            font-size: 20px;
            font-weight: bold;
            color: #333;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #667eea;
        }

        .upload-area {
            border: 2px dashed #667eea;
            border-radius: 8px;
            padding: 40px;
            text-align: center;
            background: #f8f9ff;
            cursor: pointer;
            transition: all 0.3s;
            margin-bottom: 20px;
        }

        .upload-area:hover {
            border-color: #764ba2;
            background: #f0f2ff;
        }

        .upload-area.dragover {
            border-color: #4caf50;
            background: #e8f5e9;
        }

        .upload-icon {
            font-size: 48px;
            color: #667eea;
            margin-bottom: 10px;
        }

        .upload-text {
            font-size: 16px;
            color: #666;
            margin-bottom: 10px;
        }

        .upload-hint {
            font-size: 12px;
            color: #999;
        }

        input[type="file"] {
            display: none;
        }

        .file-info {
            background: #f5f5f5;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            display: none;
        }

        .file-info.show {
            display: block;
        }

        .file-name {
            font-size: 14px;
            color: #333;
            margin-bottom: 5px;
        }

        .file-size {
            font-size: 12px;
            color: #666;
        }

        .btn-group {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }

        .btn {
            flex: 1;
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            cursor: pointer;
            transition: all 0.3s;
            font-weight: bold;
        }

        .btn-secondary {
            background: white;
            color: #667eea;
            border: 2px solid #667eea;
        }

        .btn-secondary:hover {
            background: #667eea;
            color: white;
        }

        .btn-success {
            background: linear-gradient(135deg, #4caf50 0%, #2e7d32 100%);
            color: white;
        }

        .btn-success:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(76, 175, 80, 0.4);
        }

        .btn-success:disabled {
            background: #ccc;
            cursor: not-allowed;
            transform: none;
        }

        .btn-warning {
            background: linear-gradient(135deg, #ff9800 0%, #f57c00 100%);
            color: white;
        }

        .btn-warning:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(255, 152, 0, 0.4);
        }

        .btn-warning:disabled {
            background: #ccc;
            cursor: not-allowed;
            transform: none;
        }

        .mode-hint {
            background: #f5f5f5;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
            font-size: 13px;
            display: none;
        }

        .mode-hint.show {
            display: block;
        }

        .hint-item {
            padding: 8px 0;
            color: #666;
        }

        .hint-item strong {
            color: #333;
        }

        .result-box {
            background: #f5f5f5;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            display: none;
        }

        .result-box.show {
            display: block;
        }

        .result-box.success {
            background: #e8f5e9;
            border-left: 4px solid #4caf50;
        }

        .result-box.error {
            background: #ffebee;
            border-left: 4px solid #f44336;
        }

        .result-title {
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 10px;
        }

        .result-box.success .result-title {
            color: #2e7d32;
        }

        .result-box.error .result-title {
            color: #c62828;
        }

        .result-stats {
            font-size: 14px;
            color: #666;
            margin-bottom: 10px;
        }

        .error-list {
            max-height: 300px;
            overflow-y: auto;
            background: white;
            padding: 10px;
            border-radius: 4px;
            margin-top: 10px;
        }

        .error-item {
            padding: 8px;
            margin-bottom: 5px;
            background: #fff3cd;
            border-left: 3px solid #ff9800;
            border-radius: 4px;
            font-size: 13px;
            color: #856404;
        }

        .loading {
            display: none;
            text-align: center;
            padding: 20px;
        }

        .loading.show {
            display: block;
        }

        .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #667eea;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 10px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .progress-bar {
            width: 100%;
            height: 4px;
            background: #e0e0e0;
            border-radius: 2px;
            overflow: hidden;
            margin-top: 10px;
            display: none;
        }

        .progress-bar.show {
            display: block;
        }

        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #667eea, #764ba2);
            width: 0%;
            transition: width 0.3s;
        }

        .info-box {
            background: #fff9e6;
            padding: 15px;
            border-radius: 8px;
            border-left: 4px solid #ffc107;
            margin-bottom: 20px;
        }

        .info-box h4 {
            font-size: 14px;
            font-weight: bold;
            color: #f57c00;
            margin-bottom: 10px;
        }

        .info-box ul {
            font-size: 13px;
            color: #666;
            line-height: 1.8;
            padding-left: 20px;
        }

        .info-box li {
            margin-bottom: 5px;
        }

        @media (max-width: 768px) {
            .btn-group {
                flex-direction: column;
            }
            .tabs {
                flex-direction: column;
            }
            .tab {
                min-width: auto;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📊 数据Excel导入系统</h1>
            <p>快速批量导入项目、员工、合同人员数据到数据库</p>
        </div>

        <!-- 用户信息栏 -->
        <div class="user-info" id="userInfo" style="display: none;">
            <div>
                <span class="username">👤 <span id="usernameDisplay"></span></span>
            </div>
            <div>
                <button class="logout-btn" onclick="logout()">退出登录</button>
            </div>
        </div>

        <div class="tabs">
            <div class="tab active" onclick="switchTab('project')">📋 项目数据</div>
            <div class="tab" onclick="switchTab('employee-active')">👥 在职员工</div>
            <div class="tab" onclick="switchTab('employee-resigned')">👤 离职员工</div>
            <div class="tab" onclick="switchTab('contract-personnel')">📝 合同人员</div>
        </div>

        <!-- 项目数据导入 -->
        <div id="project" class="tab-content active">
            <div class="card">
                <div class="card-title">📤 上传项目Excel文件</div>
                
                <div class="upload-area" data-type="project">
                    <div class="upload-icon">📁</div>
                    <div class="upload-text">点击或拖拽Excel文件到此处上传</div>
                    <div class="upload-hint">支持.xlsx和.xls格式，文件大小不超过10MB</div>
                    <input type="file" accept=".xlsx,.xls">
                </div>

                <div class="file-info">
                    <div class="file-name">📄 <span class="file-name-text"></span></div>
                    <div class="file-size">📦 大小：<span class="file-size-text"></span></div>
                </div>

                <div class="btn-group">
                    <button class="btn btn-secondary" onclick="downloadTemplate('project')">📥 下载模板</button>
                    <button class="btn btn-success import-btn" disabled onclick="importFile('project', false)">➕ 新增导入</button>
                    <button class="btn btn-warning update-btn" disabled onclick="importFile('project', true)">🔄 更新导入</button>
                </div>
                
                <div class="mode-hint">
                    <div class="hint-item"><strong>➕ 新增导入：</strong>只导入新项目，已存在的项目编码会被跳过</div>
                    <div class="hint-item"><strong>🔄 更新导入：</strong>已存在的项目会被更新，不存在的会新增</div>
                </div>

                <div class="loading"><div class="spinner"></div><div>正在导入，请稍候...</div></div>
                <div class="progress-bar"><div class="progress-fill"></div></div>
                <div class="result-box"></div>

                <div class="info-box">
                    <h4>⚠️ 注意事项</h4>
                    <ul>
                        <li>项目编码必须唯一，不能重复</li>
                        <li>项目名称为必填项</li>
                        <li>日期格式：YYYY-MM-DD（如：2024-01-01）</li>
                    </ul>
                </div>
            </div>
        </div>

        <!-- 在职员工导入 -->
        <div id="employee-active" class="tab-content">
            <div class="card">
                <div class="card-title">📤 上传在职员工Excel文件</div>
                
                <div class="upload-area" data-type="employee-active">
                    <div class="upload-icon">📁</div>
                    <div class="upload-text">点击或拖拽Excel文件到此处上传</div>
                    <div class="upload-hint">支持.xlsx和.xls格式，文件大小不超过10MB</div>
                    <input type="file" accept=".xlsx,.xls">
                </div>

                <div class="file-info">
                    <div class="file-name">📄 <span class="file-name-text"></span></div>
                    <div class="file-size">📦 大小：<span class="file-size-text"></span></div>
                </div>

                <div class="btn-group">
                    <button class="btn btn-secondary" onclick="downloadTemplate('employee-active')">📥 下载模板</button>
                    <button class="btn btn-success import-btn" disabled onclick="importFile('employee-active', false)">➕ 新增导入</button>
                    <button class="btn btn-warning update-btn" disabled onclick="importFile('employee-active', true)">🔄 更新导入</button>
                </div>
                
                <div class="mode-hint">
                    <div class="hint-item"><strong>➕ 新增导入：</strong>只导入新员工，已存在的身份证号会被跳过</div>
                    <div class="hint-item"><strong>🔄 更新导入：</strong>已存在的员工会被更新，不存在的会新增</div>
                </div>

                <div class="loading"><div class="spinner"></div><div>正在导入，请稍候...</div></div>
                <div class="progress-bar"><div class="progress-fill"></div></div>
                <div class="result-box"></div>

                <div class="info-box">
                    <h4>⚠️ 注意事项</h4>
                    <ul>
                        <li>姓名和身份证号为必填项</li>
                        <li>身份证号必须唯一，18位有效格式</li>
                        <li>员工数据较多，建议分批导入</li>
                    </ul>
                </div>
            </div>
        </div>

        <!-- 离职员工导入 -->
        <div id="employee-resigned" class="tab-content">
            <div class="card">
                <div class="card-title">📤 上传离职员工Excel文件</div>
                
                <div class="upload-area" data-type="employee-resigned">
                    <div class="upload-icon">📁</div>
                    <div class="upload-text">点击或拖拽Excel文件到此处上传</div>
                    <div class="upload-hint">支持.xlsx和.xls格式，文件大小不超过10MB</div>
                    <input type="file" accept=".xlsx,.xls">
                </div>

                <div class="file-info">
                    <div class="file-name">📄 <span class="file-name-text"></span></div>
                    <div class="file-size">📦 大小：<span class="file-size-text"></span></div>
                </div>

                <div class="btn-group">
                    <button class="btn btn-secondary" onclick="downloadTemplate('employee-resigned')">📥 下载模板</button>
                    <button class="btn btn-success import-btn" disabled onclick="importFile('employee-resigned', false)">➕ 新增导入</button>
                    <button class="btn btn-warning update-btn" disabled onclick="importFile('employee-resigned', true)">🔄 更新导入</button>
                </div>
                
                <div class="mode-hint">
                    <div class="hint-item"><strong>➕ 新增导入：</strong>只导入新离职员工，已存在的身份证号会被跳过</div>
                    <div class="hint-item"><strong>🔄 更新导入：</strong>已存在的离职员工会被更新，不存在的会新增</div>
                </div>

                <div class="loading"><div class="spinner"></div><div>正在导入，请稍候...</div></div>
                <div class="progress-bar"><div class="progress-fill"></div></div>
                <div class="result-box"></div>

                <div class="info-box">
                    <h4>⚠️ 注意事项</h4>
                    <ul>
                        <li>姓名和身份证号为必填项</li>
                        <li>身份证号必须唯一，18位有效格式</li>
                        <li>建议记录离职日期和离职原因</li>
                    </ul>
                </div>
            </div>
        </div>

        <!-- 合同人员导入 -->
        <div id="contract-personnel" class="tab-content">
            <div class="card">
                <div class="card-title">📤 上传合同人员Excel文件</div>
                
                <div class="upload-area" data-type="contract-personnel">
                    <div class="upload-icon">📁</div>
                    <div class="upload-text">点击或拖拽Excel文件到此处上传</div>
                    <div class="upload-hint">支持.xlsx和.xls格式，文件大小不超过10MB</div>
                    <input type="file" accept=".xlsx,.xls">
                </div>

                <div class="file-info">
                    <div class="file-name">📄 <span class="file-name-text"></span></div>
                    <div class="file-size">📦 大小：<span class="file-size-text"></span></div>
                </div>

                <div class="btn-group">
                    <button class="btn btn-secondary" onclick="downloadTemplate('contract-personnel')">📥 下载模板</button>
                    <button class="btn btn-success import-btn" disabled onclick="importFile('contract-personnel', false)">➕ 新增导入</button>
                    <button class="btn btn-warning update-btn" disabled onclick="importFile('contract-personnel', true)">🔄 更新导入</button>
                </div>
                
                <div class="mode-hint">
                    <div class="hint-item"><strong>➕ 新增导入：</strong>只导入新合同人员，已存在的会被跳过</div>
                    <div class="hint-item"><strong>🔄 更新导入：</strong>已存在的合同人员会被更新，不存在的会新增</div>
                </div>

                <div class="loading"><div class="spinner"></div><div>正在导入，请稍候...</div></div>
                <div class="progress-bar"><div class="progress-fill"></div></div>
                <div class="result-box"></div>

                <div class="info-box">
                    <h4>⚠️ 注意事项</h4>
                    <ul>
                        <li>合同ID、姓名、类型、角色、部门为必填项</li>
                        <li>合同ID+姓名+角色组合唯一</li>
                        <li>开始日期和结束日期不能为空</li>
                    </ul>
                </div>
            </div>
        </div>
    </div>

    <script>
        const API_CONFIG = {
            'project': '/api/project',
            'employee-active': '/api/employee-active',
            'employee-resigned': '/api/employee-resigned',
            'contract-personnel': '/api/contract-personnel'
        };

        const selectedFiles = {};
        let currentTab = 'project';

        document.addEventListener('DOMContentLoaded', function() {
            initAllUploadAreas();
        });

        function initAllUploadAreas() {
            document.querySelectorAll('.upload-area').forEach(area => {
                const type = area.getAttribute('data-type');
                const fileInput = area.querySelector('input[type="file"]');
                const tabContent = document.getElementById(type);

                area.addEventListener('click', () => fileInput.click());
                fileInput.addEventListener('change', (e) => handleFileSelect(type, e.target.files[0], tabContent));

                area.addEventListener('dragover', (e) => {
                    e.preventDefault();
                    area.classList.add('dragover');
                });

                area.addEventListener('dragleave', () => area.classList.remove('dragover'));
                
                area.addEventListener('drop', (e) => {
                    e.preventDefault();
                    area.classList.remove('dragover');
                    handleFileSelect(type, e.dataTransfer.files[0], tabContent);
                });
            });
        }

        function handleFileSelect(type, file, tabContent) {
            if (!file) return;

            const fileName = file.name.toLowerCase();
            if (!fileName.endsWith('.xlsx') && !fileName.endsWith('.xls')) {
                alert('⚠️ 文件格式错误，请上传Excel文件（.xlsx或.xls）');
                return;
            }

            if (file.size > 10 * 1024 * 1024) {
                alert('⚠️ 文件大小超过10MB，请选择较小的文件');
                return;
            }

            selectedFiles[type] = file;

            tabContent.querySelector('.file-name-text').textContent = file.name;
            tabContent.querySelector('.file-size-text').textContent = formatFileSize(file.size);
            tabContent.querySelector('.file-info').classList.add('show');
            tabContent.querySelector('.import-btn').disabled = false;
            tabContent.querySelector('.update-btn').disabled = false;
            tabContent.querySelector('.mode-hint').classList.add('show');
            tabContent.querySelector('.result-box').classList.remove('show');
        }

        function formatFileSize(bytes) {
            if (bytes < 1024) return bytes + ' B';
            if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + ' KB';
            return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
        }

        function switchTab(tabName) {
            currentTab = tabName;
            document.querySelectorAll('.tab').forEach(tab => tab.classList.remove('active'));
            document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
            
            event.target.classList.add('active');
            document.getElementById(tabName).classList.add('active');
        }

        async function importFile(type, isUpdateMode) {
            const file = selectedFiles[type];
            if (!file) {
                alert('⚠️ 请先选择文件');
                return;
            }

            const tabContent = document.getElementById(type);
            const modeName = isUpdateMode ? '更新模式' : '新增模式';
            const apiUrl = `${API_CONFIG[type]}/import${isUpdateMode ? '-update' : ''}`;

            const formData = new FormData();
            formData.append('file', file);

            const loading = tabContent.querySelector('.loading');
            const progressBar = tabContent.querySelector('.progress-bar');
            const progressFill = tabContent.querySelector('.progress-fill');
            const importBtn = tabContent.querySelector('.import-btn');
            const updateBtn = tabContent.querySelector('.update-btn');
            const resultBox = tabContent.querySelector('.result-box');

            loading.querySelector('div:last-child').textContent = `正在导入（${modeName}），请稍候...`;
            loading.classList.add('show');
            importBtn.disabled = true;
            updateBtn.disabled = true;
            resultBox.classList.remove('show');
            progressBar.classList.add('show');

            let progress = 0;
            const progressInterval = setInterval(() => {
                progress += 10;
                if (progress >= 90) clearInterval(progressInterval);
                progressFill.style.width = progress + '%';
            }, 200);

            try {
                // 获取Token
                const token = localStorage.getItem('token');
                if (!token) {
                    throw new Error('未登录，请先登录');
                }

                const response = await fetch(apiUrl, { 
                    method: 'POST', 
                    headers: {
                        'Authorization': 'Bearer ' + token
                    },
                    body: formData 
                });
                
                // 检查是否是401未授权
                if (response.status === 401) {
                    throw new Error('登录已过期，请重新登录');
                }
                
                const result = await response.json();

                clearInterval(progressInterval);
                progressFill.style.width = '100%';

                setTimeout(() => {
                    loading.classList.remove('show');
                    progressBar.classList.remove('show');
                    progressFill.style.width = '0%';
                    displayResult(tabContent, result, modeName);
                    importBtn.disabled = false;
                    updateBtn.disabled = false;
                }, 500);

            } catch (error) {
                console.error('导入失败:', error);
                clearInterval(progressInterval);
                loading.classList.remove('show');
                progressBar.classList.remove('show');
                importBtn.disabled = false;
                updateBtn.disabled = false;
                displayResult(tabContent, { code: 0, message: '导入失败：' + error.message }, modeName);
            }
        }

        function displayResult(tabContent, result, modeName) {
            const resultBox = tabContent.querySelector('.result-box');

            if (result.code === 200 && result.data && result.data.success) {
                const data = result.data;
                resultBox.className = 'result-box show success';
                
                let title = '✅ ' + data.message + ` (${modeName})`;
                let stats = data.updateCount !== undefined && data.updateCount > 0
                    ? `新增：${data.successCount} 条，更新：${data.updateCount} 条，失败：${data.failCount} 条`
                    : `成功导入：${data.successCount} 条，失败：${data.failCount} 条`;

                let errorHtml = '';
                if (data.errors && data.errors.length > 0) {
                    errorHtml = '<div class="error-list">' + 
                        data.errors.map(err => `<div class="error-item">⚠️ ${err}</div>`).join('') +
                        '</div>';
                }

                resultBox.innerHTML = `
                    <div class="result-title">${title}</div>
                    <div class="result-stats">${stats}</div>
                    ${errorHtml}
                `;
            } else {
                resultBox.className = 'result-box show error';
                resultBox.innerHTML = `
                    <div class="result-title">❌ 导入失败</div>
                    <div class="result-stats">${result.message || '未知错误'}</div>
                `;
            }

            resultBox.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
        }

        async function downloadTemplate(type) {
            try {
                const response = await fetch(`${API_CONFIG[type]}/template`);
                if (!response.ok) throw new Error('下载失败');

                const blob = await response.blob();
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                
                const fileNames = {
                    'project': '项目导入模板.xlsx',
                    'employee-active': '在职员工导入模板.xlsx',
                    'employee-resigned': '离职员工导入模板.xlsx',
                    'contract-personnel': '合同人员导入模板.xlsx'
                };
                
                a.download = fileNames[type];
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                window.URL.revokeObjectURL(url);

                alert('✅ 模板下载成功！');
            } catch (error) {
                console.error('下载模板失败:', error);
                alert('❌ 下载模板失败：' + error.message);
            }
        }

        // 检查登录状态
        async function checkLoginStatus() {
            const token = localStorage.getItem('token');
            const username = localStorage.getItem('username');
            
            if (!token || !username) {
                // 未登录，跳转到登录页
                alert('⚠️ 请先登录才能使用数据导入功能');
                window.location.href = '/login.html';
                return false;
            }

            // 验证Token是否有效
            try {
                const response = await fetch('/api/user/validate', {
                    headers: {
                        'Authorization': 'Bearer ' + token
                    }
                });
                
                if (response.status === 401) {
                    // Token已失效
                    localStorage.clear();
                    alert('⚠️ 登录已过期，请重新登录');
                    window.location.href = '/login.html';
                    return false;
                }
                
                const result = await response.json();
                
                if (result.code === 200) {
                    // 检查是否为管理员
                    if (!result.data.administrator || result.data.administrator == 0) {
                        alert('⚠️ 权限不足：只有管理员可以使用数据导入功能');
                        window.location.href = '/home.html';
                        return false;
                    }
                    
                    // Token有效且是管理员，显示用户信息
                    document.getElementById('usernameDisplay').textContent = username + ' (管理员)';
                    document.getElementById('userInfo').style.display = 'flex';
                    return true;
                } else {
                    // Token无效
                    localStorage.clear();
                    alert('⚠️ 登录已过期，请重新登录');
                    window.location.href = '/login.html';
                    return false;
                }
            } catch (error) {
                console.error('验证登录状态失败:', error);
                alert('❌ 验证登录状态失败，请重新登录');
                window.location.href = '/login.html';
                return false;
            }
        }

        // 退出登录
        async function logout() {
            const token = localStorage.getItem('token');
            
            if (token) {
                try {
                    await fetch('/api/user/logout', {
                        method: 'POST',
                        headers: {
                            'Authorization': 'Bearer ' + token
                        }
                    });
                } catch (error) {
                    console.error('退出登录失败:', error);
                }
            }
            
            // 清除本地存储
            localStorage.clear();
            
            // 跳转到登录页
            alert('✅ 已退出登录');
            window.location.href = '/login.html';
        }

        // 立即检查登录状态（在页面加载前）
        (function() {
            const token = localStorage.getItem('token');
            const username = localStorage.getItem('username');
            
            if (!token || !username) {
                // 未登录，立即跳转
                alert('⚠️ 请先登录才能使用数据导入功能');
                window.location.href = '/login.html';
            }
        })();

        // 页面加载时验证Token有效性
        window.addEventListener('DOMContentLoaded', async () => {
            await checkLoginStatus();
        });
    </script>
</body>
</html>

